// threadpool.hpp
#pragma once
#include <string>
#include <vector>
#include <queue>
#include <pthread.h>
#include <unistd.h>

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template <class T>
class ThreadPool
{
    static const int defaultnum = 3;

private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Tsleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : _threads)
        {
            if (ti.tid == tid)
                return ti.name;
        }
        return nullptr;
    }

public:
    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();
            while (tp->IsQueueEmpty())
            {
                tp->Tsleep();
            }
            T t = tp->pop();
            tp->Unlock();

            t();
        }
    }
    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; ++i)
        {
            _threads[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    }
    T pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    void Push(const T &t)
    {
        Lock();
        _tasks.push(t);
        Wakeup();
        Unlock();
    }

    // 获取单例对象的接口
    static ThreadPool<T> *GetInstance(int num = defaultnum)
    {
        // 双层判断，单例创建出来之后，往后的线程在这里if判断失败，直接返回，省去了加锁的步骤
        if (_tp == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if (_tp == nullptr) // 第一次并发申请锁的线程只有一个能进去，剩下的if判断失败，跳过
            {
                std::cout << "log: singleton create done first!" << std::endl;
                _tp = new ThreadPool<T>(num);
            }
            pthread_mutex_unlock(&_lock);
        }
        return _tp;
    }

private:
    ThreadPool(int num = defaultnum)
        : _threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    ThreadPool(const ThreadPool<T> &) = delete;
    const ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _tasks;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _lock;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;

// 以上是一个单例线程池的实现
// int n = 10;
// ThreadPool<Task> *p = ThreadPool<Task>::GetInstance(n);
// 获取单例对象，只是初始化了锁和条件变量，并没有真的创建多线程

// ThreadPool<Task>::GetInstance(n)->Start();
// 启动线程池，自动创建n个线程，因为此时没有任务，线程会加入等待队列

// Task t();
// ThreadPool<Task>::GetInstance()->Push(t);
// 创建并push任务，push之后会自动叫醒一个线程来执行该任务，执行完后，该线程会再次休眠
